using B.S.XZYData.Api.Wrter.Application.Command.WorkOrder;
using B.S.XZYData.Domain.LJC;
using B.S.XZYData.ErrorCode;
using B.S.XZYData.Infrastructure.Interface;
using MediatR;
using Microsoft.Extensions.Logging;
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Transactions;

namespace B.S.XZYData.Api.Wrter.Application.Handler.WorkOrder
{
    /// <summary>
    /// 批量删除工单处理器
    /// </summary>
    public class BatchDeleteWorkOrderHandler : IRequestHandler<BatchDeleteWorkOrderCommand, ApiResult<bool>>
    {
        private readonly IBaseRepository<WorkOrderModel> _workOrderRepo;
        private readonly IBaseRepository<WorkOrderProcessModel> _workOrderProcessRepo;
        private readonly IBaseRepository<WorkOrderAssignModel> _workOrderAssignRepo;
        private readonly ILogger<BatchDeleteWorkOrderHandler> _logger;

        public BatchDeleteWorkOrderHandler(
            IBaseRepository<WorkOrderModel> workOrderRepo,
            IBaseRepository<WorkOrderProcessModel> workOrderProcessRepo,
            IBaseRepository<WorkOrderAssignModel> workOrderAssignRepo,
            ILogger<BatchDeleteWorkOrderHandler> logger)
        {
            _workOrderRepo = workOrderRepo;
            _workOrderProcessRepo = workOrderProcessRepo;
            _workOrderAssignRepo = workOrderAssignRepo;
            _logger = logger;
        }

        public async Task<ApiResult<bool>> Handle(BatchDeleteWorkOrderCommand request, CancellationToken cancellationToken)
        {
            var res = new ApiResult<bool>();

            try
            {
                // 设置默认操作人
                if (string.IsNullOrWhiteSpace(request.OperateBy))
                {
                    request.OperateBy = "System";
                }

                // 参数验证
                if (request.Ids == null || !request.Ids.Any())
                {
                    res.Code = ApiEnum.Error;
                    res.Msg = "请选择要删除的工单";
                    return res;
                }

                // 获取要删除的工单
                var workOrders = _workOrderRepo.GetAll()
                    .Where(x => request.Ids.Contains(x.Id))
                    .ToList();

                if (!workOrders.Any())
                {
                    res.Code = ApiEnum.Error;
                    res.Msg = "未找到要删除的工单";
                    return res;
                }

                using (var scope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
                {
                    int deletedCount = 0;

                    foreach (var workOrder in workOrders)
                    {
                        try
                        {
                            // 获取该工单的所有工序
                            var processes = _workOrderProcessRepo.GetAll()
                                .Where(x => x.WorkOrderId == workOrder.Id)
                                .ToList();

                            // 删除所有相关的分派记录
                            foreach (var process in processes)
                            {
                                var assigns = _workOrderAssignRepo.GetAll()
                                    .Where(x => x.WorkOrderProcessId == process.Id)
                                    .ToList();

                                foreach (var assign in assigns)
                                {
                                    await _workOrderAssignRepo.DeleteAsync(assign.Id);
                                }
                            }

                            // 删除所有工序记录
                            foreach (var process in processes)
                            {
                                await _workOrderProcessRepo.DeleteAsync(process.Id);
                            }

                            // 删除工单主记录
                            await _workOrderRepo.DeleteAsync(workOrder.Id);

                            deletedCount++;
                            _logger.LogInformation($"删除工单：{workOrder.Code}，操作人：{request.OperateBy}");
                        }
                        catch (Exception ex)
                        {
                            _logger.LogError(ex, $"删除工单失败：{workOrder.Code}，操作人：{request.OperateBy}");
                            // 继续删除其他工单，不中断整个过程
                        }
                    }

                    scope.Complete();

                    res.Data = true;
                    res.Code = ApiEnum.Success;
                    res.Msg = $"批量删除完成，成功删除 {deletedCount} 个工单";
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"批量删除工单失败，操作人：{request.OperateBy}");
                res.Code = ApiEnum.Error;
                res.Msg = $"批量删除工单失败：{ex.Message}";
            }

            return res;
        }
    }
}
